
//获取应用实例
var app = getApp();

Page({
    data: {


        ordersLength: 0,
        inputValue: "",
        importordersLength: 0,
        allordersLength: 0,
        tabArr: {
            curHdIndex: 0,
            curBdIndex: 0
        },
        isShare:'',
        currentTab: 0,
        tabArray: ["已审订单", "未审订单", "订单汇总"],

        isShow1: true,
        isShow2: false,
        showPulldown: false,
        isFixed: false,
        isshow_subsidy: true,
        minprice: '',
        maxprice: '',
        showMotal: false,

        sort: 0,
        cname: "",
        sortName: "默认",
        currentTab: 0,
        currentTab2: 0,
        hiddenLoading: false,
        indicatorDots: true,
        autoplay: true,
        interval: 3000,
        from_uid: 0,
        nickname: '',
        memberid: 0,
        datalock: false,
        uri: "list",
        searchkey: "",
        showAnimation: false,
        globalset: {

        },
        homeskinid: -1,
        duration: 100,
        "banner": [
        ],
        commodity: [

        ],
        goodCarousel: [

        ],
        goodCarousel2: [

        ],
        imgmenu: [
        ],
        imgmenu2: [
        ],
        imgmenu3: [

        ],

    },

    onLoad: function (options) {


        //app.setTabBar();
        var $this = this;

        this.getGlobalSet();
        //控制弹窗的函数
        //调用应用实例的方法获取全局数据
        app.getUserInfo(function (userInfo) {
            //更新数据
            $this.setData({
                userInfo: userInfo
            })
        })


    },
    initIndex: function () {
        var $this = this;
        $this.goodList(1);

        //执行砍价明细函数
        //$this.ajaxGetMyCuttingDetail();
        //$this.goodList(1, "limittime", '', 0);
        //$this.goodList(1, "realtime", '', 0);

        var memberinfo = wx.getStorageSync('memberinfo');
       
        //砍价按钮内容赋值

        //if (memberinfo.)
        $this.setData({ memberinfo: memberinfo });
        var globalset = wx.getStorageSync('globalset');
        $this.setData({
            commission: 0,
            datalock: false
        });
        //计算总的佣金比例
        var total_commission = 0;
        if (globalset.memberlevel != undefined && globalset.memberlevel.length != undefined) {
            for (var i = 0; i < globalset.memberlevel.length; i++) {
               
                //当前会员类型的等级佣金比例
                if (globalset.memberlevel[i].type == memberinfo.type && globalset.memberlevel[i].name == memberinfo.level) {
                    total_commission = parseFloat(globalset.memberlevel[i].myteam_credit2) + parseFloat(globalset.memberlevel[i].myleader1_credit2) + parseFloat(globalset.memberlevel[i].myleader2_credit2);
                    //换成只取1级佣金的比例
                    total_commission = parseFloat(globalset.memberlevel[i].myteam_credit2);
                   
                    $this.setData({
                        commission: total_commission,
                        datalock: false
                    });
                 
                }
            }
        }
        if (memberinfo.type == 0) {
            if (globalset.isopen_subsidy == 0) {
                $this.setData({
                    isshow_subsidy: false
                });
            }
           
            total_commission = parseFloat(globalset.subsidy);
            $this.setData({
                commission: total_commission,
                datalock: false
            });
        }

        if (globalset.isshow_subsidy == 0) {
            $this.setData({
                isshow_subsidy: false
            });
        }
        $this.getMyFreeGoods();

       // this.getMyOrder("orders");
        //this.getMyOrder("importorders");
        this.getfreeorders();

    },
    getGlobalSet: function () {
        var $this = this;
        app.util.request({
            url: 'entry/wxapp/Global',
            showLoading: false,
            data: {
                "m": 'nets_haojk'
            },
            method: 'post',
            success: function (response) {
                var globalset = response.data.data;
                $this.setData({
                    hiddenLoading: true
                });
                $this.setData({
                    globalset: globalset,
                    homeskinid: globalset.homeskinid
                });
                wx.setStorage({
                    key: "globalset",
                    data: globalset
                });
                //banner
                var banner_str = globalset.banner;
                var banner_json = JSON.parse(banner_str);
                if (banner_json != undefined && banner_json.list != null && banner_json.list != undefined && typeof banner_json.list != undefined && banner_json.list != null && banner_json.list != '') {
                    $this.setData({
                        banner: banner_json.list,
                        datalock: false
                    });
                }
                //图标菜单
                var newhead_menu_json = [];
                var head_menu_str = globalset.head_menu;
                var head_menu_json = JSON.parse(head_menu_str);
            

                if (head_menu_json != undefined && head_menu_json.list != null && head_menu_json.list != undefined && typeof head_menu_json.list != undefined && head_menu_json.list != null && head_menu_json.list != '') {
                    var menulen = head_menu_json.list.length;
                    for (var i = 0; i < 8; i++) {
                        newhead_menu_json.push(head_menu_json.list[i])
                    }


                    $this.setData({
                        imgmenu: newhead_menu_json,
                        datalock: false

                    });


                    var imgmenu2 = new Array();
                    for (var i = 8; i < 16; i++) {
                        imgmenu2.push(head_menu_json.list[i]);
                    }
                    $this.setData({
                        imgmenu2: imgmenu2,
                        datalock: false
                    });

                    $this.setData({
                        imgmenuAll: head_menu_json.list,
                        datalock: false
                    });


                    var imgmenu22 = new Array();
                    for (var i = 16; i < menulen; i++) {
                        imgmenu22.push(head_menu_json.list[i]);
                    }
                    $this.setData({
                        imgmenu22: imgmenu22,
                        datalock: false
                    });
                    var imgmenu222 = new Array();
                    for (var i = 24; i < menulen; i++) {
                        imgmenu222.push(head_menu_json.list[i]);
                    }
                    $this.setData({
                        imgmenu222: imgmenu222,
                        datalock: false
                    });
                }

                $this.getMember();

            }
        });

    },
    getMember: function () {
        var that = this;
        app.getUserInfo(function (userInfo) {
            //更新数据
            app.util.getUserInfo(function (response) {

                response.memberInfo.nickname = userInfo.nickName;
                response.memberInfo.avatar = userInfo.avatarUrl;
                response.memberInfo.city = userInfo.city;
                response.memberInfo.country = userInfo.country;
                response.memberInfo.province = userInfo.province;
                response.memberInfo.gender = userInfo.gender;
                that.addMember(response.memberInfo);
            });
        });
        // 页面渲染完成
    },

    addMember: function (userInfo) {
        var $this = this;
        app.util.request({
            url: 'entry/wxapp/AddMember',
            showLoading: false,
            data: {
                "m": 'nets_haojk',
                "from_uid": this.data.from_uid,
                "nickname": userInfo.nickname,
                "avatar": userInfo.avatar,
                "city": userInfo.city,
                "country": userInfo.country,
                "province": userInfo.province,
                "gender": userInfo.gender,
            },
            method: 'post',
            success: function (response) {
                //首页存储会员对象到缓存，其他页面直接读取缓存即可
                wx.setStorage({
                    key: "memberinfo",
                    data: response.data.data
                });
                $this.setData({
                    memberid: response.data.data.memberid,
                    nickname: response.data.data.nickname,
                    datalock: false
                });

                $this.initIndex();

            }
        });
    },


    bindChange: function (e) {
        var that = this;
        that.setData({ currentTab: e.detail.current });

    },


    onShareAppMessage: function (res) {
        var memberinfo = wx.getStorageSync("memberinfo");
        if (res.from === 'button') {
            // 来自页面内转发按钮
        }

        return {
            title: this.data.globalset.title,
            path: '/haojk/pages/index/index?from_uid=' + memberinfo.memberid + '&from_nickname=' + memberinfo.nickname + '&type=' + memberinfo.type + '&homeskinid=' + memberinfo.homeskinid,
            success: function (res) {
                // 转发成功
            },
            fail: function (res) {
                // 转发失败
            }
        }

    },

    goodList: function (page, t, callback, goodstype) {
     
        var $this = this;
      
        var limittime = 1;
        var realtime = 1;
        if (t == "limittime") {
            realtime = "";
        } else if (t == "realtime") {
            limittime = "";
        } else {
            //  $this.setData({canBottomRefresh:true});
            limittime = "";
            realtime = "";
        }
        if ($this.data.datalock) {
            //return false;
        }
        $this.setData({
            page: page,
            datalock: true,
        });

        app.util.request({
            url: 'entry/wxapp/GetFreeGoods',
            showLoading: false,
            data: {
                m: 'nets_haojk',
                page: page,
               
            },
            method: 'post',
            success: function (response) {
                if (typeof callback == 'function') {
                    callback(response.data.data);
                   
                   
                    $this.setData({
                        datalock: false
                    });
                } else {
                 
                    var goods = response.data.data;
    
                        $this.setData({
                            commodity: goods,
                            datalock: false
                        });
                   
                }


            }
        });
    },

    //事件处理函数
    skiptodetail: function (e) {
        var $that = this;

        var skuId = e.currentTarget.dataset.skuid;
        for (var i = 0; i < this.data.commodity.length; i++) {
            if (this.data.commodity[i].skuId == skuId) {
                var good = this.data.commodity[i];
                wx.setStorage({
                    key: "good",
                    data: good
                });
            }
        }


        //加入我的免单
        app.util.request({
            url: 'entry/wxapp/SetFreeGoodsDetail',
            data: {
                m: "nets_haojk",
                skuId: skuId,
                memberid: $that.data.memberinfo.memberid
            },
            method: 'post',
            success: function (response) {
             
              if(response.data.errno==0){
                  $that.getMyFreeGoods();

                  wx.navigateTo({
                      url: '../shareFreeOrderDetail/index?skuId=' + skuId
                  })
              }
               
            }
        })

       
    },
    onReachBottom: function () {

        // var $this = this;

        // var page = $this.data.page + 1;
        // var second_height = $this.data.second_height * page;
        // $this.setData({ second_height: second_height });
        // $this.goodList(page);

    },
    choiceState: function (e) {
        var $that = this;
     
        if (e.currentTarget.dataset.state == 2) {
          
            $that.setData(
                { isShow1: false, isShow3: false,isShow2: true, },
            );
        } else if (e.currentTarget.dataset.state == 1) {
        
            $that.setData({ isShow1: true, isShow3: false, isShow2: false, }, );
        }
        else if (e.currentTarget.dataset.state == 3) {
         
            $that.setData({ isShow1: false, isShow2: false, isShow3: true, }, );
        }


    },
    getMyFreeGoods:function(){
        var $that = this;
        //加入我的免单
        app.util.request({
            url: 'entry/wxapp/SetFreeGoodsDetail',
            data: {
                m: "nets_haojk",
                skuId: 0,
                memberid: $that.data.memberinfo.memberid
            },
            method: 'post',
            success: function (response) {
                var obj = response.data.data;
             
                if(response.data.errno==0){
                    //$that.setData({ myFreeGoods: response.data.data});
                }
             

               
                setInterval(function(){
                    for (var i = 0; i < obj.length; i++) {
                        //obj[i].createtime = countTime(obj[i].createtime);
                        obj[i].showdaojishi = countTime(obj[i].createtime);    
                       // obj[i].lessMoney = (obj[i].wlPrice_after - obj[i].yikan).toFixed(2); 
                   
                        if (obj[i].yikan == 0) {
                            obj[i].lijibuy = 1;
                            obj[i].showdaojishi00 = true
                           
                        } else {
                            obj[i].lijibuy = 0;
                            obj[i].showdaojishi00 = false

                        }

                      
                    }

                    
                },1000)

                

              

                //倒计时函数
                function countTime(a) {
                    var daojishi = parseInt(a)+1*24*60*60; 
                  
                  
                    var timestamp = Date.parse(new Date()) / 1000;
               
                    daojishi = daojishi - timestamp;
                    var leftTime = daojishi;
                
                    var d, h, m, s;
                    if (leftTime >= 0) {
                        d = Math.floor(leftTime / 60 / 60 / 24);
                        h = Math.floor(leftTime / 60 / 60 % 24);
                        m = Math.floor(leftTime / 60 % 60);
                        s = Math.floor(leftTime % 60);
                    }else{
                        d = '00';
                        h = '00';
                        m = '00';
                        s = '00';
                    };
             
                    $that.setData({ myFreeGoods: obj })
                    return h+':'+m+':'+s
                    //  var timer = hh + mm + ss;
                    daojishi = daojishi - 1;
                   
                }
             // setTimeout(countTime, 3000);

               
              
                    

                   
                

             
                   
             
                

            }
        })
    },
  
    //事件处理函数
    tabFun: function (e) {
        var $that = this;
        //获取触发事件组件的dataset属性  
        var _datasetId = e.target.dataset.id;
        var _obj = {};
        _obj.curHdIndex = _datasetId;
        _obj.curBdIndex = _datasetId;
        this.setData({
            tabArr: _obj
        });
     
        if (_obj.curHdIndex == 0) {
            //$that.getMyOrder("orders");
        } else if (_obj.curHdIndex == 1) {
        
            //$that.getMyOrder("importorders");
        } else if (_obj.curHdIndex == 2) {
            //$that.getMyOrder("orders");
        }
    },
    //事件处理函数
    bindViewTap: function () {
        wx.navigateTo({
            url: '../detail/index'
        })
    },
    //获取我的订单列表

    getfreeorders:function(){
        var memberinfo = wx.getStorageSync('memberinfo');
       
        var $that = this;
        app.util.request({
            url: 'entry/wxapp/Getfreeorders',
            data: {
                m: "nets_haojk",
                memberid: memberinfo.memberid
            },
            method: 'post',
            success: function (response) {
              
                var obj = response.data.data;
                for (var i = 0; i < obj.length; i++) {
                    obj[i].created_at = form_time(obj[i].created_at);
                }
         
                    $that.setData({
                        importordersArray: obj,
                    });
             
                //int转时间戳
                function form_time(a) {
                    var myDate = new Date(parseInt(a) * 1000);
                    var datestr = "";
                    datestr = myDate.getFullYear();    //获取完整的年份(4位,1970-????)
                    datestr = datestr + "-" + (myDate.getMonth() + 1);       //获取当前月份(0-11,0代表1月)
                    datestr = datestr + "-" + myDate.getDate();        //获取当前日(1-31)
                    datestr = datestr + " " + myDate.getHours();
                    datestr = datestr + ":" + myDate.getMinutes();
                    datestr = datestr + ":" + myDate.getSeconds();

                    return datestr;
                }

            }
        })
    },

    //提交订单函数
    startSubmit: function () {
        var $that = this;
     
        if ($that.data.inputValue == null || $that.data.inputValue == undefined || $that.data.inputValue == "") {
            wx.showModal({
                title: '提示',
                content: '订单号不能为空',
                success: function (res) {
                    if (res.confirm) {
                     
                        $that.getfreeorders();
                    } else if (res.cancel) {
                      
                    }
                }
            })

        } else {
            app.util.request({
                url: 'entry/wxapp/Freeordersubmit',
                data: {
                    m: 'nets_haojk',
                    orderno: $that.data.inputValue,
                    memberid: $that.data.memberinfo.memberid


                },
                method: 'post',
                success: function (response) {
                    if(response.data.data==1){
                        wx.showModal({
                            title: '提示',
                            content: "提单成功，请等待审核",
                            success: function (res) {
                                if (res.confirm) {
                                    $that.getfreeorders();
                                
                                } else if (res.cancel) {
                                 
                                }
                            }
                        })
                    }
                   
                }
            })
        }



    },

    changeInput: function (e) {
        this.setData({ inputValue: e.detail.value })
        if (this.data.borderShow) {
            this.setData({ borderShow: false })
        }

       
    }
  
})



